import re

from django import http
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect, render
from django.urls import reverse

from django.views import View
from django_redis import get_redis_connection
from pymysql import DatabaseError

from apps.users.models import User, Address


class UsercenterView(LoginRequiredMixin, View):
    def get(self, request):
        """
        个人中心
        """

        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
        }
        return render(request, 'user_center_info.html', context=context)


class UserRegisterrView(View):
    def get(self, request):
        """
        注册页面
        """
        return render(request, 'register.html')

    def post(self, request):
        # 获取数据

        username = request.POST.get('user_name')
        password = request.POST.get('pwd')
        password2 = request.POST.get('pwd2')
        email = request.POST.get('email')
        mobile = request.POST.get('mobile')

        allow = request.POST.get('allow')

        # 进行判断
        if not all([username, password, password2, allow]):
            return http.HttpResponseBadRequest('缺少必穿参数')
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return http.HttpResponseBadRequest('请输入5-20个字符的用户名')
        if not re.match(r'^[0-9A-Za-z]{8,20}', password):
            return http.HttpResponseBadRequest('请输入8-20位的密码')
        # 判断两次密码是否一致
        if password != password2:
            return http.HttpResponseBadRequest('两次输入的密码不一样')
        # 判断是否勾选用户协议
        if allow != 'on':
            return http.HttpResponseBadRequest('请勾选用户协议')
        # if not re.match(r'^1[3-9]\d{9}', mobile):
        #     return http.HttpResponseBadRequest('请输入正确的手机号')

        # redis_conn = get_redis_connection('code')
        # sms_code_saved = redis_conn.get('sms_%s' % mobile)
        # if sms_code_saved is None:
        #     return render(request, 'register.html', {'sms_code_errmsg': '无效的短信验证码'})
        # if sms_code != sms_code_saved.decode():
        #     return render(request, 'register.html', {'sms_code_errmsg': '输入短信验证码有误'})

        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile, email=email)
        except DatabaseError:
            return render(request, 'register.html', {'register_errmsg': '注册失败'})

        login(request, user)
        # return redirect(reverse('index:index'))
        return http.HttpResponseRedirect('/')
        # return redirect('/')


class LoginView(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        '''获取数据'''
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        '''判断数据'''
        if not all([username, password]):
            return http.HttpResponseBadRequest('缺少必传参数')
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return render(request, 'login.html', {'account_msg': '请输入正确的用户名或手机号'})
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return render(request, 'login.html', {'account_msg': '请输入正确的密码'})
        # 认证用户
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_msg': '用户名或密码错误'})
        login(request, user)

        # 响应登录结果
        # response = http.HttpResponseRedirect(reverse('index:index'))

        # return redirect(reverse('index:index'))
        # response = http.HttpResponseRedirect('/')
        # response = redirect('/')

        return http.HttpResponseRedirect('/')


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        """实现退出登录逻辑"""
        # 清理session
        logout(request)

        # 退出登录，重定向到登录页
        response = http.HttpResponseRedirect('/')

        return response


class AddressView(View):
    """用户收货地址"""

    def get(self, request):
        """提供收货地址界面"""
        user = request.user
        try:
            address = Address.objects.filter(user=user)
        except:
            address = None
        data = {
            "address": address,
        }
        return render(request, 'user_center_site.html', data)

    def post(self, request):
        addressee = request.POST.get('addressee')
        address_dz = request.POST.get('address_dz')
        telephone = request.POST.get('telephone')
        try:
            address = Address.objects.create(
                user=request.user,
                receiver=addressee,
                title=address_dz,
            )

        except Exception as e:
            return http.JsonResponse({'code': '001', 'errmsg': '新增数据失败'})
        #     # 5.返回数据到页面
        # address_dict = {
        #     'id': address.id,
        #     'title': address.title,
        #     'receiver': address.receiver,
        #     'province_id': address.province_id,
        #     'city_id': address.city_id,
        #     'district_id': address.district_id,
        #     'place': address.place,
        #     'mobile': address.mobile,
        #     'tel': address.tel,
        #     'email': address.email
        # }
        return http.HttpResponseRedirect('/address')
